package com.sptokentest.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sptokentest.pj.dto.UserDto;
import com.sptokentest.entity.User;
import com.sptokentest.service.UserService;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.awt.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.sptokentest.utils.RedisConstants.CAPTCHA_CODE_KEY;
import static com.sptokentest.utils.RedisConstants.LOGIN_CODE_TTL;

@Slf4j
@RestController
@RequestMapping("/common/")
public class CommonController {
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 登录操作
     * @param user
     * @return
     */
    @PostMapping("login")
    public SaResult login(@RequestBody UserDto user) {
        String username = user.getUsername();
        String password = user.getPassword();
//        String code;
//        try {
//            code = stringRedisTemplate.opsForValue().get(user.getKey());
//        } catch (Exception e) {
//            return SaResult.error("验证码超时,请刷新重试");
//        }
//        log.info(username+password+code);
//        if(!user.getCode().equals(code)){
//            return SaResult.error("验证码错误，请重新输入");
//        }
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getUsername,username);
        User checkUser = userService.getOne(lqw);
        if(checkUser==null){
            return SaResult.error("用户名不存在");
        }
        if(checkUser.getStatus()==0){
            return SaResult.error("账户已被停用,请联系管理员");
        }
        if(!checkUser.getPassword().equals(password)){
            return SaResult.error("用户名或密码错误");
        }
        StpUtil.login(checkUser.getId());
        //删除缓存验证码
        stringRedisTemplate.delete(user.getKey());
        return SaResult.data(checkUser);
    }

    /**
     * 注销登录
     * @return
     */
    @GetMapping("logout")
    public SaResult logout() {
        StpUtil.logout();
        return SaResult.ok();
    }

    /**
     * 获取验证码
     */
    @GetMapping ("captcha")
    public SaResult captcha(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
        // 设置请求头为输出图片类型
        response.setContentType("image/gif");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        // 三个参数分别为宽、高、位数
        SpecCaptcha specCaptcha = new SpecCaptcha(150, 40, 5);
        // 设置字体
        specCaptcha.setFont(new Font("Verdana", Font.PLAIN, 32));  // 有默认字体，可以不用设置
        // 设置类型，纯数字、纯字母、字母数字混合
        specCaptcha.setCharType(Captcha.TYPE_ONLY_NUMBER);

        String verCode = specCaptcha.text().toLowerCase();
        String key = CAPTCHA_CODE_KEY + UUID.randomUUID().toString();
//        request.setAttribute(key,verCode);
//        session.setAttribute(key,verCode);
        stringRedisTemplate.opsForValue().set(key,verCode,LOGIN_CODE_TTL, TimeUnit.MINUTES);
        String image = specCaptcha.toBase64();
        HashMap<String,String> map = new HashMap<>();
        map.put("key",key);
        map.put("image",image);
        return SaResult.data(map);
    }
}
